<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-form-item label="班组名称" prop="name">
        <el-input v-model="formItem.name" placeholder="请输入班组名称" />
      </el-form-item>
      <el-form-item label="颜色" prop="color">
        <el-color-picker v-model="formItem.color" show-alpha />
      </el-form-item>
      <el-form-item label="管理部门" prop="orgCode">
        <TreeSelect
          v-model="formItem.orgCode"
          :multiple="false"
          :options="availableOganizations"
          placeholder="请选择管理部门"
          @select="selcetOrg"
          @input="inputOrg"
        />
      </el-form-item>
      <el-form-item label="职能" prop="functionalGroupId">
        <el-select v-model="formItem.functionalGroupId" clearable filterable remote placeholder="请选择职能" @change="groupChange">
          <el-option v-for="(item) in functionalGroupList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="成员组成" prop="users">
        <el-button size="mini" icon="el-icon-plus" @click="handleUserClick">添加</el-button>
      </el-form-item>
      <PageableTable :loading="false" :table-height="300" :data="formItem.users" :disable-pageable="true" class="fixed-table-table">
        <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
          <template slot-scope="scope">
            <column-render :render="column.render" :row="scope.row" :column="column" />
          </template>
        </el-table-column>
        <el-table-column label="是否为管理" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-select v-model="row.isManager" filterable remote placeholder="请选择是否为管理">
              <el-option v-for="(item) in managerType" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="text" title="删除" size="mini" icon="el-icon-delete" @click="remove(row)" />
          </template>
        </el-table-column>
      </PageableTable>
    </el-form>
    <SelectDialog v-if="userSelDialogFormVisible" title="选择人员" :append-to-body="true" :show="userSelDialogFormVisible" @on-ok="selectUserOk" @on-cancel="selectUserCancel">
      <UsersPage ref="usersTable" :for-selection="true" :multiple-selected="true" :functional-group-id="formItem.functionalGroupId" />
    </SelectDialog>
  </div>
</template>

<script>
import {
  create,
  update,
  detail
} from '@neu/dcom-ui/api/teamgroup'
import { list } from '@neu/dcom-ui/api/functional'
import TreeSelect from '@neu/biz-core/components/TreeSelect'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import UsersPage from '@neu/dcom-ui/views/functional/components/userTable'
import PageableTable from '@neu/biz-core/components/PageableTable'
import { userTree as tree } from '@neu/auth-ui/api/organization'
// 定义一个表单原始项
const formItem = {
  name: '',
  orgName: '',
  orgCode: null,
  functionalGroupId: '',
  color: null,
  users: []
}
export default {
  name: 'TeamgroupEditForm',
  components: {
    PageableTable,
    UsersPage,
    SelectDialog,
    TreeSelect
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      managerType: [
        { name: '是', code: true },
        { name: '否', code: false }
      ],
      insideColumns: [
        { title: '人员名称', key: 'name' },
        { title: '人员编码', key: 'code' }
      ],
      // 职能列表
      functionalGroupList: [],
      // 人员选择弹窗
      userSelDialogFormVisible: false,
      /** 使用部门 */
      availableOganizations: [],
      /** 是否初始化 */
      isUpdateInit: true,
      // 表单验证规则
      rules: {
        name: [{
          required: true,
          message: '班组名称不能为空',
          trigger: 'blur'
        },
        {
          validator: function(rule, value, callback) {
            if (value.length > 100) {
              callback(new Error('最多可输入100个字符'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        orgCode: [{
          required: true,
          message: '管理部门不能为空',
          trigger: 'blur'
        }],
        color: [{
          required: true,
          message: '颜色不能为空',
          trigger: 'blur'
        }],
        functionalGroupId: [{
          required: true,
          message: '职能不能为空',
          trigger: 'blur'
        }],
        users: [{
          required: true,
          message: '至少选择一个人员',
          trigger: 'blur'
        },
        {
          validator: function(rule, value, callback) {
            if (value.length < 1) {
              callback(new Error('至少选择一个人员'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }]
      },
      modal: true
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
    tree().then(response => {
      this.availableOganizations = [...response.data]
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.isUpdateInit = false
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            // 至少组内含有一个人员校验
            if (this.formItem.users.length < 1) {
              this.$message({
                showClose: true,
                message: '至少选择一个人员',
                type: 'error'
              })
              return resolve(false)
            }
            // 组内人员至少有一个管理者、
            const fileterData = this.formItem.users.filter(e => e.isManager === true)
            if (fileterData.length < 1) {
              this.$message({
                showClose: true,
                message: '至少指定一个人员为管理者',
                type: 'error'
              })
              return resolve(false)
            }
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
      formItem.users = []
    },
    handleUserClick() {
      if (this.formItem.functionalGroupId) {
        this.userSelDialogFormVisible = true
      } else {
        this.$message({
          showClose: true,
          message: '请选择职能',
          type: 'warning'
        })
      }
    },
    selectUserOk() {
      var users = this.$refs.usersTable.selections
      if (users.length < 1) {
        return this.$message({
          showClose: true,
          message: '至少选择一个人员',
          type: 'error'
        })
      }
      users.forEach(l => {
        const isExist = this.formItem.users.filter(m => m.code === l.code).length < 1
        if (isExist) {
          this.formItem.users.push({ name: l.name, code: l.code, isManager: false })
        } else {
          this.formItem.users.forEach(s => {
            if (s.code === l.code) {
              s.name = l.name
            }
          })
        }
      })

      this.userSelDialogFormVisible = false
    },
    selectUserCancel() {
      this.userSelDialogFormVisible = false
    },
    remove(row) {
      this.formItem.users = this.formItem.users.filter(ele => ele.code !== row.code)
    },
    /** 组织机构赋值 */
    selcetOrg(value) {
      this.formItem.orgName = value.title
    },
    inputOrg(value) {
      if (this.isUpdateInit) {
        this.formItem.users = []
        this.formItem.functionalGroupId = ''
        this.functionalGroupList = []
      }
      this.isUpdateInit = true
      if (value === undefined) {
        this.formItem.orgName = ''
      } else {
        list({ 's_orgCode': value }).then(res => {
          this.functionalGroupList = res.data
        })
      }
    },
    // 职能发生改变的时候清空列表
    groupChange(value) {
      this.formItem.users = []
    }
  }
}
</script>
